package com.hjm.framework.websocket;

//import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.websocket.*;
        import java.io.*;
        import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName WebSocketStompConfig
 * @Version 1.0
 **/
/*@Slf4j
@Component
//@ServerEndpoint(value = "/websocket/logging")*/
public class WebSocket {
    /**
     * 连接集合
     */
    private static Map<String, Session> sessionMap = new ConcurrentHashMap<String, Session>();
    private static Map<String, Integer> lengthMap = new ConcurrentHashMap<String, Integer>();

    private Process process;
    private InputStream inputStream;



    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        try {
            process = Runtime.getRuntime().exec("tail -f /home/makerweb/makerplatform/logs/cataline.out");
            inputStream = process.getInputStream();
            //开启一个新线程防止阻塞
            WebSocketThread thread = new WebSocketThread(inputStream, session);
            thread.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        //从集合中删除
        sessionMap.remove(session.getId());
        lengthMap.remove(session.getId());
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) {

    }

    /**
     * 封装一个send方法，发送消息到前端
     */
    private void send(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        String filePath = "C://home/maker/logs/sys_business1.log";
        try {
            /*Process exec = Runtime.getRuntime().exec("CMD /C tail -f " +
                    "D://tomcat/apache-tomcat-8.5.54/apache-tomcat-8.5.54/logs/catalina.2021-03-10.out");*/

            Process exec = Runtime.getRuntime().exec("calc.exe");
            InputStream inputStream = exec.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            System.out.println(reader.readLine());
            Object[] lines = reader.lines().toArray();
            for (Object line : lines) {

                System.out.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
